<template>
  <div class="about-page">
    <h1>体重管理</h1>
    <!-- 表格 -->
    <div class="weight-records-table">
      <table>
        <thead>
          <tr>
            <th>weight（体重）</th>
            <th>record_date（记录日期）</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(record, index) in weightRecords" :key="record.weight_id">
            <td>{{ record.weight }}</td>
            <td>{{ formatDate(record.record_date) }}</td>
            <td>
              <button @click="deleteWeightRecord(record)" class="nav-link-like">
                <i class="fa fa-trash mr-2"></i> 删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-if="weightRecords.length === 0" class="text-center py-8 text-gray-500">
        <i class="fa fa-info-circle mr-2"></i> 暂无体重记录
      </div>
    </div>
    <!-- 添加体重记录表单 -->
    <div class="add-record-form mt-6 p-4 bg-white rounded-lg shadow-md">
      <h3 class="text-lg font-semibold mb-4 text-center">添加体重记录</h3>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">体重 (kg)</label>
          <input
            v-model.number="newRecord.weight"
            type="number"
            step="0.1"
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            placeholder="输入体重"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">记录日期</label>
          <input
            v-model="newRecord.recordDate"
            type="date"
            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
      </div>
      <button
        @click="addWeightRecord"
        class="mt-4 block mx-auto nav-link-like"
      >
        <i class="fa fa-plus mr-2"></i> 添加记录
      </button>
    </div>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading text-center mt-4">
      <i class="fa fa-spinner fa-spin mr-2"></i> 加载中...
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/stores/counter'; // 引入用户store

const userStore = useUserStore(); // 创建用户store实例
const weightRecords = ref([]);
const loading = ref(false);
const newRecord = ref({
  weight: null,
  recordDate: new Date().toISOString().split('T')[0], // 默认今天
});

// 格式化日期（处理时间戳）
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleDateString('zh-CN');
};

// 获取体重记录（修改接口路径为weight_record/all）
const fetchWeightRecords = async () => {
  loading.value = true;
  try {
    const user_id = userStore.userId;
    console.log('当前获取的user_id（fetchWeightRecords）:', user_id);
    if (!user_id) {
      console.error('用户未登录，无法获取体重记录');
      alert('请先登录');
      return;
    }
    
    const response = await axios.get('http://localhost:8080/MDMS0214_war/weight_record/all');
    if (response.status === 200) {
      // 直接使用后端返回的record_date时间戳
      const filteredRecords = response.data.filter(record => record.user_id === user_id);
      weightRecords.value = filteredRecords; // 直接赋值，无需转换字段名
      console.log('获取到的体重记录数据:', weightRecords.value);
    } else {
      console.error('获取体重记录接口返回非200状态码:', response.status);
      alert('获取体重记录失败，请稍后重试');
    }
  } catch (error) {
    console.error('获取体重记录失败:', error);
    alert('获取体重记录失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 添加体重记录（修改接口路径为weight_record/add，并调整字段名）
const addWeightRecord = async () => {
  // 表单验证
  if (!newRecord.value.weight || !newRecord.value.recordDate) {
    alert('请填写体重和日期');
    return;
  }

  try {
    const user_id = userStore.userId;
    console.log('当前获取的user_id（addWeightRecord）:', user_id);
    if (!user_id) {
      alert('请先登录');
      return;
    }

    // 准备数据（使用record_date时间戳字段）
    const date = new Date(newRecord.value.recordDate);
    const data = {
      user_id: user_id, // 保持与后端字段一致（假设后端为user_id）
      weight: newRecord.value.weight,
      record_date: date.getTime() // 转换为时间戳
    };

    // 调用后端接口（修改路径为weight_record/add）
    const response = await axios.post('http://localhost:8080/MDMS0214_war/weight_record/add', data, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    if (response.status === 200) {
      if (response.data > 0) {
        alert('添加成功');
        // 刷新数据
        fetchWeightRecords();
        // 重置表单
        newRecord.value.weight = null;
        newRecord.value.recordDate = new Date().toISOString().split('T')[0];
      } else {
        alert('添加失败');
      }
    } else {
      console.error('添加体重记录接口返回非200状态码:', response.status);
      alert('添加体重记录失败，请稍后重试');
    }
  } catch (error) {
    console.error('添加体重记录失败:', error);
    alert('添加体重记录失败，请稍后重试');
  }
};

// 删除体重记录（修改接口路径为weight_record/{weight_id}）
const deleteWeightRecord = async (record) => {
  if (!window.confirm('确定要删除这条记录吗？')) {
    return;
  }

  try {
    const user_id = userStore.userId;
    console.log('当前获取的user_id（deleteWeightRecord）:', user_id);
    if (!user_id) {
      alert('请先登录');
      return;
    }
    // 使用weightId构建URL（修改路径为weight_record/{weight_id}）
    const response = await axios.delete(`http://localhost:8080/MDMS0214_war/weight_record/${record.weight_id}`, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    if (response.status === 200) {
      if (response.data > 0) {
        alert('删除成功');
        // 刷新数据
        fetchWeightRecords();
      } else {
        alert('删除失败');
      }
    } else {
      console.error('删除体重记录接口返回非200状态码:', response.status);
      alert('删除体重记录失败，请稍后重试');
    }
  } catch (error) {
    console.error('删除体重记录失败:', error);
    alert('删除体重记录失败，请稍后重试');
  }
};

// 页面加载时获取数据
onMounted(fetchWeightRecords);
</script>

<style scoped>
/* 样式部分保持不变，无需修改 */
.about-page {
  font-family: Arial, sans-serif;
  padding: 20px;
}

.weight-records-table {
  border-collapse: collapse;
  width: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20px;
}

.weight-records-table th, 
.weight-records-table td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}

h1 {
  text-shadow: 0 0 5px white;
  text-align: center;
  margin-bottom: 30px;
}

.loading {
  font-size: 18px;
}

/* 添加记录表单样式优化 */
.add-record-form {
  border-radius: 20px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.18);
  background-color: #fff;
  border: 2px solid #f0f0f0;
  overflow: hidden;
  max-width: 500px;
  margin: 0 auto 30px;
}

.add-record-form h3 {
  color: #333;
  border-bottom: 2px solid #ccc;
  padding-bottom: 12px;
  margin-bottom: 20px;
}

.add-record-form label {
  color: #555;
  font-weight: 500;
}

.add-record-form input {
  border: 1px solid #ddd;
  border-radius: 10px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06);
  padding: 14px;
  font-size: 16px;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.add-record-form input:focus {
  border-color: #007bff;
  box-shadow: 0 0 10px rgba(0, 123, 255, 0.35);
}

.nav-link-like {
  background-color: #69cbcb;
  color: white;
  text-decoration: none;
  font-size: 16px;
  transition: color 0.3s ease;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.nav-link-like:hover {
  color: #ffcc00;
}

/* 表单字段容器样式 */
.add-record-form .grid-cols-1 md\:grid-cols-2 {
  gap: 24px;
}

/* 输入框和按钮的响应式样式 */
@media (max-width: 768px) {
 .add-record-form .grid-cols-1 md\:grid-cols-2 {
    grid-template-columns: 1fr;
  }
}
</style>